package com.example.aimnear;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView;

public class FullscreenActivity extends Activity
{	
	
	private ListView tasksListView;
	private Button addTaskButton;
	private EditText taskNameText;
	private Map<String,String> IdAndName = new HashMap<String,String>();
	private List<String> IdsOfAproproatePosotion = new ArrayList<String>();
	private List<String> valuesForList = new ArrayList<String>();
	private ArrayAdapter<String> tasksListAdapter;
	private DbInterface dataBaseCall;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.dataBaseCall = new DbInterface(this);
		setContentView(R.layout.activity_fullscreen);
		this.taskNameText = (EditText)findViewById(R.id.editText1);
		setList();
		setButton();
	}
	@Override
	protected void onDestroy () 
	{
		super.onDestroy();
		this.dataBaseCall.closeBaseConnection();
	}
	
	protected void setList()
	{
		tasksListView = (ListView) findViewById(R.id.listView1);
		getContentForList();
		tasksListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, valuesForList);
		tasksListView.setAdapter(tasksListAdapter);
		tasksListView.setLongClickable(true);
		tasksListView.setOnItemLongClickListener(
				new OnItemLongClickListener()
				{
					public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
					{
						dataBaseCall.deleteTask(Integer.valueOf(IdsOfAproproatePosotion.get(position)));
						IdAndName.remove(IdsOfAproproatePosotion.get(position));
						IdsOfAproproatePosotion.remove(position);
						valuesForList.remove(position);
						tasksListAdapter.notifyDataSetChanged();
						return true;
					}
				});
	}

	protected void setButton()
	{
		System.out.println("set Button");
		addTaskButton = (Button)findViewById(R.id.button1);
		addTaskButton.setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0)
					{
						String taskName = taskNameText.getText().toString().trim();
						if(!(taskName.length()==0))
							dataBaseCall.addTask(taskName, null);
						getContentForList();
						tasksListAdapter.notifyDataSetChanged();
						taskNameText.setText("");
					}
				}
		);
	}
	
	private void getContentForList () {
		IdsOfAproproatePosotion.clear();
		valuesForList.clear();
		IdAndName = dataBaseCall.selectOpenTasks();
		for (String id: IdAndName.keySet()){ 
			IdsOfAproproatePosotion.add(id);
			valuesForList.add(IdAndName.get(id));
		}
	}
}
